package com.jichaoyun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jichaoyun.common.model.PagedResult;
import com.jichaoyun.common.enums.MyExceptiontType;
import com.jichaoyun.common.ex.MyException;
import com.jichaoyun.dao.mapper.*;
import com.jichaoyun.model.entity.PriceChange;
import com.jichaoyun.model.entity.Rechargeinfo;
import com.jichaoyun.model.entity.StationInfo;
import com.jichaoyun.model.vo.PriceChangeModel;
import com.jichaoyun.service.IPriceChangeService;

import java.math.BigDecimal;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


import com.jichaoyun.service.util.SmsSendService;
import com.jichaoyun.service.util.TcpUtils.TcpConnect;
import com.jichaoyun.service.util.TcpUtils.TcpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author zhen
 * @description 针对表【price_change】的数据库操作Service实现
 * @createDate 2023-12-08 19:50:38
 */
@Service
@Slf4j
public class PriceChangeServiceImpl extends ServiceImpl<PriceChangeMapper, PriceChange> implements IPriceChangeService {

    @Autowired
    private RechargeinfoMapper rechargeinfoMapper;

    @Autowired
    private RealdataMapper realdataMapper;

    @Autowired
    private StationInfoMapper stationInfoMapper;
    private BigDecimal newPrice;

    @Autowired
    private SmsCacheMapper smsCacheMapper;

    /**
     * 查询汽费记录
     *
     * @param pageNo
     * @return
     */
    @Override
    public PagedResult selectPriceChangeListByPage(Integer pageNo) {
        Page<PriceChange> page = new Page<>(pageNo, 10);
        QueryWrapper<PriceChange> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("start_time");
        Page<PriceChange> priceChangePage = this.baseMapper.selectPage(page, wrapper);
        PagedResult pagedResult = new PagedResult();
        pagedResult.setTotal(priceChangePage.getTotal());
        pagedResult.setPages(priceChangePage.getPages());
        pagedResult.setRows(priceChangePage.getRecords());
        return pagedResult;
    }

    /**
     * 汽费调整
     *
     * @param model
     */
    @Override
    @Transactional
    public void startPriceChange(PriceChangeModel model) {
        StationInfo stationInfo = this.stationInfoMapper.selectById(model.getStationId());
        if (stationInfo == null) {
            throw new MyException(MyExceptiontType.Other, "站点ID不正确");
        }
        PriceChange entity = new PriceChange();
        entity.setIsUse(false);
        entity.setStartTime(model.getStartTime());
        entity.setUnitPrice(model.getNewPrice());
        entity.setStationName(stationInfo.getStationName());
        entity.setStationId(model.getStationId());
        this.baseMapper.insert(entity);
    }

    /**
     * 批量汽费调整
     *
     * @param models
     */
    @Override
    public void startPriceChange(List<PriceChangeModel> models) {
        for (PriceChangeModel model : models) {
            startPriceChange(model);
        }
    }


    /**
     * 结算调整
     *
     * @param pageNo
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public PagedResult selectTotalBetween(Integer pageNo, LocalDateTime startTime, LocalDateTime endTime) {
        PagedResult pagedResult = new PagedResult();
        Page<StationInfo> stationIPage = new Page<>(pageNo, 10);
        QueryWrapper<StationInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("station_no");
        Page<StationInfo> StationInfoPage = this.stationInfoMapper.selectPage(stationIPage, queryWrapper);
        List<HashMap<String, Object>> resMaplist = new ArrayList<>();
        List<StationInfo> StationInfoList = StationInfoPage.getRecords();
        for (StationInfo stationInfo : StationInfoList) {
            HashMap<String, Object> listMap = new HashMap<>();
            Integer result = this.realdataMapper.selectTotalBetweenTime(stationInfo.getStationNo(), startTime, endTime);
            listMap.put("stationId", stationInfo.getStationNo());
            listMap.put("stationName", stationInfo.getStationName());
            listMap.put("total", result);
            listMap.put("price", stationInfo.getPrice());
            resMaplist.add(listMap);
        }
        pagedResult.setRows(resMaplist);
        pagedResult.setPages(StationInfoPage.getPages());
        pagedResult.setTotal(StationInfoPage.getTotal());
        return pagedResult;
    }

//    /**
//     * 辅助充值
//     * @param stationId
//     * @param num
//     */
//    @Override
//    @Transactional
//    public void recharge(Integer stationId, @NotNull BigDecimal num, ChargeType type) throws Exception {
//        //往dtu中写充值命令
//        if(TcpConnect.clientInfoMap.containsKey(stationId)){
//            StationInfo stationInfo = this.stationInfoMapper.selectById(stationId);
//            try {
//                Socket socket = TcpConnect.clientInfoMap.get(stationId);
//                TcpUtil tcpUtil = new TcpUtil();
//                //往现场的设备进行充值
////                System.out.println(socket);
////                System.out.println(stationInfo.getComPassword());
////                System.out.println(stationInfo.getAddr());
//                tcpUtil.recharge(num.floatValue(),socket.getOutputStream(),stationInfo.getComPassword(),stationInfo.getAddr());
////                System.out.println("充值成功"+num);
//            }catch (Exception e){
//                throw new MyException(MyExceptiontType.STATIONOUTLINE,null);
//            }
//            //插入充值信息
//            Rechargeinfo info = new Rechargeinfo();
//            info.setReChargeValue(num);
//            info.setBalance(newPrice);
//            info.setChargeType(type.getCnName());
//            info.setStationName(stationInfo.getStationName());
//            StringBuilder remark = new StringBuilder(stationInfo.getStationName());
//            remark.append(type.getCnName()).append(num.toString()).append("元");
//            info.setRemark(remark.toString());
//            info.setStationNo(stationId);
//            LocalDateTime now = LocalDateTime.now();
//            LocalDateTime datetime = LocalDateTime.of(now.toLocalDate(),now.toLocalTime().withNano(0));
//
//            info.setTime(datetime);
//            info.setIsRead(false);
//            rechargeinfoMapper.insert(info);
//
//            //发送充值成功的信息
//            String tel = stationInfo.getTel().trim();
//
//            String name = stationInfo.getStationName().trim();
//
//            SmsSendService.in_sms_recharge(tel,name,num,LocalDateTime.now(),newPrice,stationId);
//        }else{
//            throw new MyException(MyExceptiontType.STATIONOUTLINE,null);
//        }
//
//    }


    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public void recharge(Rechargeinfo rechargeinfo) throws Exception {
        //往dtu中写充值命令
        Integer stationNo = rechargeinfo.getStationNo();
        Integer addr = stationInfoMapper.selectById(stationNo).getAddr();
        TcpConnect.if_recharge[stationNo] = false;
        if(TcpConnect.clientInfoMap.containsKey(rechargeinfo.getStationNo())){
            new TcpUtil().readData(TcpConnect.clientInfoMap.get(stationNo).getOutputStream(),addr);
        }else {
            log.error(rechargeinfo.getStationName() + "站点已掉线,充值失败");
            throw new MyException(MyExceptiontType.STATIONOUTLINE, null);
        }

        while (!TcpConnect.if_recharge[stationNo]){
            Thread.sleep(10);
        }

        if (TcpConnect.if_recharge[stationNo]) {
            StationInfo stationInfo = this.stationInfoMapper.selectById(rechargeinfo.getStationNo());
            try {
                Socket socket = TcpConnect.clientInfoMap.get(rechargeinfo.getStationNo());
                TcpUtil tcpUtil = new TcpUtil();
                //往现场的设备进行充值
//                System.out.println(socket);
                tcpUtil.recharge(rechargeinfo.getReChargeValue().floatValue(), socket.getOutputStream(), stationInfo.getComPassword(), stationInfo.getAddr());
                rechargeinfo.setIsRead(true);
                rechargeinfo.setBalance(stationInfo.getBalance());
                int rows = rechargeinfoMapper.updateById(rechargeinfo);
                //发送充值成功的信息
                String tel = stationInfo.getTel().trim();
                String name = stationInfo.getStationName().trim();
                SmsSendService.in_sms_recharge(tel, name, rechargeinfo.getReChargeValue(), LocalDateTime.now(), rechargeinfo.getBalance(), rechargeinfo.getStationNo());
            } catch (Exception e) {
                throw e;
            }
        } else {
            log.error(rechargeinfo.getStationName() + "站点已掉线,充值失败");
            throw new MyException(MyExceptiontType.STATIONOUTLINE, null);
        }

    }
}




